import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import * as config from 'config';

import { IS_PUBLIC_KEY } from './decorator/public';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private reflector: Reflector, private jwtService: JwtService) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    // 先判断 某些特殊的情况下   直接让通过
    const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) return true;
    const request = context.switchToHttp().getRequest();
    if (!request.headers.authorization) {
      throw new UnauthorizedException('请登录');
    }
    const [type, token] = request.headers.authorization?.split(' ');
    if (!token) {
      throw new UnauthorizedException('请县登录');
    }
    try {
      const payload = await this.jwtService.verifyAsync(token, {
        secret: config.get('secretOrKey'),
      });
      request.userInfo = payload;
    } catch (e) {
      throw new UnauthorizedException('请登录');
    }
    return true;
  }
}
